<template>
  <div class="app-container" style="margin-top: -25px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
     <!-- <el-form-item label="采购单号" prop="caigouDanhao">
        <el-input
          v-model="queryParams.caigouDanhao"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编码" prop="itemId">
        <el-input
          v-model="queryParams.itemId"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplyName">
        <el-input
          v-model="queryParams.supplyName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="大类Id" prop="classId">
        <el-input
          v-model="queryParams.classId"
          placeholder="请输入大类Id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="大类名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入大类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购日期" prop="caigouDate">
        <el-date-picker clearable
          v-model="queryParams.caigouDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采购日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>-->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >选择物料</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:caigouDetail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:caigouDetail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:caigouDetail:export']"
        >导出</el-button>
      </el-col>-->
<!--
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
-->
    </el-row>
    <el-table  v-loading="loading"  :summary-method="getSummaries" show-summary :data="caigouDetailList" @selection-change="handleSelectionChange" row-key="columnId" :max-height="tableHeight">
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="spec" />
      <el-table-column label="单位" align="center" prop="unit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jc_iteminfo_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
<!--
      <el-table-column label="物料编码" align="center" prop="itemId" />
-->
<!--
      <el-table-column label="供应商编码" align="center" prop="supplyId" />
-->
<!--
      <el-table-column label="供应商名称" align="center" prop="supplyName" />
-->
      <el-table-column label="采购数量" align="center" prop="caigouNum" >
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input  clearable style="display:inline"v-model="scope.row.caigouNum"></el-input>
          </div>
        </template>
      </el-table-column>
     <!--   <el-table-column label="采购单价"  align="center" prop="unitPrice" >
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input-number style="width: 100%"  controls-position="right" clearable v-model="scope.row.unitPrice" :precision="2"></el-input-number>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="采购总价"  align="center" prop="totalPrice">
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.unitPrice*scope.row.caigouNum | numFilter}}</span>
          </div>
        </template>
      </el-table-column>-->
      <!--<el-table-column label="备注" align="center" prop="remark">
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input   clearable style="display:inline"v-model="scope.row.remark"></el-input>
          </div>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:caigouDetail:edit']"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index,scope.row)"
            v-hasPermi="['business:caigouDetail:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

   <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />-->

    <!-- 添加或修改采购详情对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" style="margin-top: -20px"  :model="form" :rules="rules" label-width="80px">
        <IteminfoSelect ref="iteminfoSelect"></IteminfoSelect>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">选 择</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCaigouDetail, getCaigouDetail,addCaigoItemInfo, delCaigouDetail, addCaigouDetail, updateCaigouDetail } from "@/api/business/caigouDetail";
import IteminfoSelect from '@/views/base/iteminfo/iteminfoSelect';
import { getIteminfoByIds } from "@/api/base/iteminfo";

export default {
  components: {
    IteminfoSelect
  },
  name: "CaigouDetail",
  dicts: ['jc_iteminfo_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      itemIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购详情表格数据
      caigouDetailList: [],
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caigouDanhao: null,
        itemName: null,
        itemId: null,
        supplyName: null,
        classId: null,
        className: null,
        caigouDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
   /* this.getList();*/
  },
  filters: {
    numFilter (value) {
      // 截取当前数据到小数点后两位
      let realVal = parseFloat(value).toFixed(2)
      return realVal
    }
  },
  methods: {
    /** 查询采购详情列表 */
    getList() {
      this.loading = true;
      listCaigouDetail(this.queryParams).then(response => {
        this.caigouDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCgInfoList(danhao){
      this.queryParams.caigouDanhao=danhao;
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        caigouDanhao: null,
        itemName: null,
        itemId: null,
        supplyId: null,
        supplyName: null,
        classId: null,
        className: null,
        caigouNum: null,
        unitPrice: null,
        totalPrice: null,
        caigouDate: null,
        unit: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if (index === 1 || index === 2 || index === 3 || index === 7) {
          return '';
        }
        for(var i=0 ;i<data.length;i++){
          data[i].totalPrice =data[i].caigouNum*data[i].unitPrice;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if(index==4){
                return prev + curr
              }else{
                return this.keepTwoDecimalFull(Number(prev) + curr);
              }
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    keepTwoDecimalFull(num) {
      var result = parseFloat(num);
      if (isNaN(result)) {
        alert('传递参数错误，请检查！');
        return false;
      }
      result = Math.round(num * 100) / 100;
      var s_x = result.toString(); //将数字转换为字符串

      var pos_decimal = s_x.indexOf('.'); //小数点的索引值


      // 当整数时，pos_decimal=-1 自动补0
      if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
      }

      // 当数字的长度< 小数点索引+2时，补0
      while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
      }
      return s_x;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /*重置列表*/
    listReset(){
      this.caigouDetailList =[];
      this.loading = false;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "选择物料信息";
      this.itemIds=[];
      if(this.caigouDetailList.length>0){
        this.caigouDetailList.map((item) => {
          this.itemIds.push(item.itemCode);
        })
      }
      setTimeout(() => {
        this.$refs.iteminfoSelect.getItemInfoList(this.itemIds);
      }, 5);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCaigouDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const id =this.$refs.iteminfoSelect.ids;
      addCaigoItemInfo(id).then(response => {
        response.data.map((item)=>{
          this.caigouDetailList.push(item)
        })
      });
      this.open = false;
    },
    /** 删除按钮操作 */
    handleDelete(index,row) {
      this.caigouDetailList.splice(index,1);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/caigouDetail/export', {
        ...this.queryParams
      }, `采购单导出_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  ::v-deep .el-input-number.is-controls-right .el-input-number__increase{
    display: none;
    visibility: hidden;
    width: 10px !important;
    position: fixed;
    top:0;
  }
  ::v-deep .el-input-number.is-controls-right .el-input-number__decrease{
    display: none;
    visibility: hidden;
    position: fixed;
    top:0;
  }
  ::v-deep .el-table .cell{
    /*display: none;*/
    padding-right: 0;
    padding-left: -30px;
  }
</style>
